package com.mach.platform.repository;

import com.mach.platform.domain.base.Role;
import org.springframework.data.jpa.repository.Modifying;
import org.springframework.data.jpa.repository.Query;
import org.springframework.stereotype.Repository;

import java.util.List;
import java.util.Map;

/**
 * @author Anonymous
 * @Description:
 * @Package: com.mach.platform.com.mach.platform.repository
 * @time 2018/04/12 17:44
 */

@Repository
public interface RoleRepo extends BaseRepository<Role> {

	/**
	 * 角色表级联太多，重要的字段不多，直接更新对象影响甚大，故由此简单更新重要字段的方法
	 * @param name
	 * @param remark
	 * @param updateTime
	 * @param updateBy
	 * @param roleId
	 * @return
	 */
	@Modifying
	@Query(value = "update role set name=?1,remark=?2,updateTime=?3,updateBy=?4 where id=?5",nativeQuery = true)
	Integer updateSomeFields (String name, String remark,String updateTime,String updateBy,Long roleId);

	/**
	 * 加载用户所拥有的角色
	 * @param username
	 * @return
	 */
	@Query(value = "select r.id,r.content,r.name from role_account ar  join account a on a.id=ar.account_id join role r on r.id =ar.role_id where a.username = ?1", nativeQuery = true)
	List<Map> loadUserRolesByUserName (String username);

	/**
	 * 跟新数据前，删除对应的数据
	 * @param roleId
	 * @return
	 */
	@Modifying
	@Query(value = "delete from role_account where role_id = ?1 and account_id != 1", nativeQuery = true)
	int delUserRelationByRoleId (Long roleId);

    /**
     * 跟新数据前，删除对应的数据 (非删除角色) 菜单
     * @param roleId
     * @return
     */
    @Modifying
    @Query(value = "delete from role_menu where role_id = ?1 and menu_id != 1 and menu_id != 2", nativeQuery = true)
    int delMenuRelationByRoleId (Long roleId);

	/**
	 *  清除角色相关的 菜单  数据
	 *
	 * @param roleId
	 * @return
	 */
	@Modifying
	@Query(value = "delete from role_menu where role_id = ?1", nativeQuery = true)
	int delMenuRelationByRoleIdAll (Long roleId);

}
